﻿using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.SharePoint;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;

namespace CodeCounsel.SharePoint.DevTools.ItemTypes
{
    class FullTrustProxyProperties
    {
        const string ExtensionDataKey = "CodeCounsel.SharePoint.DevTools.ItemTypes.FullTrustProxyProperties";

        ObservableCollection<FullTrustProxyOperationDefinition> _operations;
        
        public FullTrustProxy Proxy { get; private set; }
        public ISharePointProjectItem ProjectItem { get; private set; }

        public ObservableCollection<FullTrustProxyOperationDefinition> Operations
        {
            get
            {
                if (_operations == null)
                {
                    _operations = new ObservableCollection<FullTrustProxyOperationDefinition>();
                    if (ProjectItem.ExtensionData.ContainsKey(ExtensionDataKey))
                    {
                        LoadCollection(_operations, ProjectItem.ExtensionData[ExtensionDataKey]);
                    }
                    StartMonitoring(_operations);
                }
                return _operations;
            }
        }

        public FullTrustProxyProperties(FullTrustProxy proxy, ISharePointProjectItem projectItem)
        {
            Proxy = proxy;
            ProjectItem = projectItem;
        }

        void LoadCollection(ObservableCollection<FullTrustProxyOperationDefinition> operations, string data)
        {
            if (String.IsNullOrEmpty(data) == false)
            {
                string[] items = data.Split('|');
                foreach (string item in items)
                {
                    operations.Add(new FullTrustProxyOperationDefinition { FullClassName = item });
                }
            }
        }

        void SaveOperations(ObservableCollection<FullTrustProxyOperationDefinition> operations)
        {
            StringBuilder builder = new StringBuilder();
            if (operations.Count > 0)
            {
                builder.Append(operations[0].FullClassName);
                for (int i = 1; i < operations.Count; i++)
                {
                    builder.Append("|");
                    builder.Append(operations[i].FullClassName);
                }
            }
            ProjectItem.ExtensionData[ExtensionDataKey] = builder.ToString();
        }

        void StartMonitoring(ObservableCollection<FullTrustProxyOperationDefinition> operations)
        {
            operations.CollectionChanged +=
                delegate(object sender, NotifyCollectionChangedEventArgs e)
                {
                    SaveOperations((ObservableCollection<FullTrustProxyOperationDefinition>)sender);
                };
        }
    }
}
